﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;

using Baosight.ZNH.ZMCommon;
using Baosight.Platform.Core;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.ServiceModel;

using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Charting;

namespace Baosight.ZNH.ZMCE.UI
{
    public partial class ZMCEA2 : EFViewCmes
    {
        private DispatcherTimer timer = new DispatcherTimer();     //定时器
        private string chartType = "";

        public ZMCEA2()
        {
            InitializeComponent();

            this.fdBeginTime.Value = DateTime.Now.AddDays(-90).ToString(Common.DATETIME_FORMAT);
            this.fdEndTime.Value = DateTime.Now.ToString(Common.DATETIME_FORMAT);

            InitChart(this.OEEChart, "设备OEE统计图");
            InitChart(this.othersChart, "OEE各项指标统计图");

            this.Loaded += new RoutedEventHandler(ZMCEA2_Loaded);
        }

        #region 初始化，加载树目录

        /// <summary>
        /// 初始化，页面加载时，查询树目录节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ZMCEA2_Loaded(object sender, RoutedEventArgs e)
        {
            EIInfo inInfo = new EIInfo();

            inInfo.Attributes[EIConstants.ServiceNameKey] = "ZMCEA0";
            inInfo.Attributes[EIConstants.MethodNameKey] = "initLoad";

            this.Submit(inInfo, loadSubmitCompleted);
        }

        /// <summary>
        /// 返回树目录节点数据，加载树目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void loadSubmitCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                EFWindow.Alert("数据库查询数据错误，请检查服务器/数据库连接！");
                return;
            }
            else
            {
                EIInfo outInfo = e.EIInfo;

                EIBlock mineBlock = outInfo.GetBlock("mine");
                EIBlock systemBlock = outInfo.GetBlock("system");
                EIBlock deviceBlock = outInfo.GetBlock("unit");

                if ((mineBlock != null) && (systemBlock != null) && (deviceBlock != null))
                {
                    AddItemsToTree(mineBlock, systemBlock, deviceBlock);
                    this.tree.ExpandAll();
                }
                else
                {
                    return;
                }
            }
        }

        /// <summary>
        /// 添加矿井、生产系统、设备（生产单元）3级树目录结构
        /// </summary>
        /// <param name="mine"></param>
        /// <param name="system"></param>
        /// <param name="device"></param>
        private void AddItemsToTree(EIBlock mine, EIBlock system, EIBlock unit)
        {
            IList<EIRow> mineRows = mine.GetRows();

            if (mineRows.Count > 0)
            {
                IDictionary<string, EFTreeItem> mineDic = new Dictionary<string, EFTreeItem>();
                IDictionary<string, EFTreeItem> systemDic = new Dictionary<string, EFTreeItem>();

                for (int i = 0; i < mineRows.Count; i++)
                {
                    EIRow row = mineRows[i];
                    EFTreeItem item = new EFTreeItem();
                    item.eHeader = row["fdName"];
                    item.ItemObject = row;
                    item.ExpandAll();
                    this.tree.AddTreeItem(item);

                    string fdId = row["fdKeyId"].ToString().Trim();    //矿井ID
                    mineDic.Add(fdId, item);
                }

                AddChildItems(system, "fdMineId", "fdName", mineDic, systemDic);
                AddChildItems(unit, "fdProductionSystemId", "fdName", systemDic, null);
            }
        }

        /// <summary>
        /// 将Blcok中的节点添加到父节点下
        /// </summary>
        /// <param name="block"></param>
        /// <param name="parentIndex"></param>
        /// <param name="nameIndex"></param>
        /// <param name="parentDic"></param>
        /// <param name="childDic"></param>
        private void AddChildItems(EIBlock block, string parentIndex, string nameIndex,
            IDictionary<string, EFTreeItem> parentDic, IDictionary<string, EFTreeItem> childDic)
        {
            IList<EIRow> rows = block.GetRows();

            if (rows.Count > 0)
            {
                for (int i = 0; i < rows.Count; i++)
                {
                    string parentId = rows[i][parentIndex].ToString().Trim();

                    if (parentDic.ContainsKey(parentId))
                    {
                        EFTreeItem parentItem = parentDic[parentId];

                        EFTreeItem item = new EFTreeItem();
                        item.eHeader = rows[i][nameIndex];
                        item.ItemObject = rows[i];
                        item.ExpandAll();

                        parentItem.AddTreeItem(item);

                        if (childDic != null)
                        {
                            string fdId = rows[i]["fdKeyId"].ToString().Trim();    //
                            childDic.Add(fdId, item);
                        }
                    }
                }
            }
        }

        #endregion

        #region 点击树目录响应处理

        /// <summary>
        /// 点击树目录节点事件响应
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tree_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if ((sender as EFTree).SelectedItem == null)
                return;

            Common.ClearChart(this.OEEChart);
            Common.ClearChart(this.othersChart);

            this.equipmentOEEGrid.ItemsSource = null;

            EFTreeItem selectItem = (sender as EFTree).SelectedItems[0] as EFTreeItem;
            IList<EIRow> queryList = new List<EIRow>();

            if (selectItem.ParentItem != null)
            {
                if (selectItem.ParentItem.ParentItem != null)
                {
                    //EFWindow.Alert("生产单元节点！");
                    EIRow row = selectItem.ItemObject as EIRow;
                    queryList.Add(row);
                }
                else
                {
                    //EFWindow.Alert("生产系统节点！");
                    AddTreeItems(queryList, selectItem);
                }
            }
            else
            {
                //if (selectItem.IsRootItem)
                //    EFWindow.Alert("矿井节点！");
                AddTreeItems(queryList, selectItem);
            }

            EIBlock block = new EIBlock("queryBlock");
            Common.AddColumnToBlock(block, "fdKeyId");

            if (queryList.Count > 0)
            {
                AddQueryBlock(block, queryList);
                QueryOEEInfo(block);
            }
        }

        /// <summary>
        /// 遍历EFTreeItem下的所有叶子节点
        /// </summary>
        /// <param name="list"></param>
        /// <param name="treeItem"></param>
        private void AddTreeItems(IList<EIRow> list, EFTreeItem treeItem)
        {
            if (treeItem.HasItems)
            {
                ItemCollection childItems = treeItem.Items;

                for (int i = 0; i < childItems.Count; i++)
                {
                    EFTreeItem item = (EFTreeItem)childItems[i];

                    if (item.HasItems)
                    {
                        ItemCollection nextChildItems = item.Items;

                        for (int j = 0; j < nextChildItems.Count; j++)
                        {
                            EFTreeItem nextItem = (EFTreeItem)nextChildItems[j];

                            EIRow nextRow = nextItem.ItemObject as EIRow;
                            list.Add(nextRow);
                        }
                    }
                    else
                    {
                        if ((item.ParentItem != null) && (!item.ParentItem.IsRootItem))
                        {
                            EIRow row = item.ItemObject as EIRow;
                            list.Add(row);
                        }
                    }
                }
            }
            else
            {
                return;
            }
        }

        /// <summary>
        /// 拼接查询字段
        /// </summary>
        /// <param name="list"></param>
        /// <param name="treeItem"></param>
        private void AddQueryBlock(EIBlock block, IList<EIRow> list)
        {
            string euqipmentId = "'" + list[0]["fdKeyId"].ToString().Trim() + "'";

            for (int i = 1; i < list.Count; i++)
            {
                euqipmentId = euqipmentId + ", '" + list[i]["fdKeyId"].ToString().Trim() + "'";
            }

            EIRow row = new EIRow();
            row.Add("fdKeyId", euqipmentId);

            block.AddRow(row);
        }

        #endregion

        #region 查询设备OEE相关信息

        /// <summary>
        /// "查询"按钮响应事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnQueryButtonClick(object sender, RoutedEventArgs e)
        {
            string deviceNo = "";
            string deviceName = "";
            string startTime = "";
            string stopTime = "";

            if ((this.fdCode.Value != null) && (!this.fdCode.Value.ToString().Trim().Equals("")))
            {
                deviceNo = this.fdCode.Value.ToString().Trim();
            }

            if ((this.fdName.Value != null) && (!this.fdName.Value.ToString().Trim().Equals("")))
            {
                deviceName = this.fdName.Value.ToString().Trim();
            }

            if ((this.fdBeginTime != null))   //过滤开始日期可能输入的非法字符
            {
                string tmpStart = this.fdBeginTime.GetDataValue().ToString().Trim();
                this.fdBeginTime.Value = "";        //必须先置成""后，再赋值，才会在页面中生效
                this.fdBeginTime.Value = tmpStart;
            }

            if (this.fdEndTime != null)         //过滤结束日期可能输入的非法字符
            {
                string tmpEnd = this.fdEndTime.GetDataValue().ToString().Trim();
                this.fdEndTime.Value = "";      //必须先置成""后，再赋值，才会在页面中生效
                this.fdEndTime.Value = tmpEnd;
            }

            if (!GetDateTimePara(this.fdBeginTime, this.fdEndTime, ref startTime, ref stopTime))
            {
                return;
            }

            EIBlock block = new EIBlock("queryBlock");
            Common.AddColumnToBlock(block, "fdCode");
            Common.AddColumnToBlock(block, "fdName");
            Common.AddColumnToBlock(block, "fdStartTime");
            Common.AddColumnToBlock(block, "fdEndTime");

            EIRow row = new EIRow();
            row.Add("fdCode", deviceNo);
            row.Add("fdName", deviceName);
            row.Add("fdStartTime", startTime);
            row.Add("fdEndTime", stopTime);

            block.AddRow(row);

            QueryOEEInfo(block);
        }

        /// <summary>
        /// 校验、获取起始、结束日期的查询条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private bool GetDateTimePara(EFDataField fdStart, EFDataField fdEnd, ref string startTime, ref string stopTime)
        {
            startTime = "";
            stopTime = "";

            if ((fdStart != null) && (!fdStart.GetDataValue().ToString().Trim().Equals("")))
            {
                startTime = fdStart.Value.ToString().Trim() + " " + "00:00:00";
            }

            if ((fdEnd != null) && (!fdEnd.Value.ToString().Trim().Equals("")))
            {
                stopTime = fdEnd.Value.ToString().Trim() + " " + "23:59:59";
            }

            DateTime currentDate = DateTime.Parse(DateTime.Now.ToString(Common.DATETIME_FORMAT) + " " + "23:59:59");

            if ((!startTime.Equals("")) || (!stopTime.Equals("")))
            {
                if ((!startTime.Equals("")) && (!stopTime.Equals("")))
                {
                    DateTime beginTime = Convert.ToDateTime(startTime);
                    DateTime endTime = Convert.ToDateTime(stopTime);

                    if (beginTime.CompareTo(currentDate) > 0 || endTime.CompareTo(currentDate) > 0)
                    {
                        EFWindow.Alert("选择日期不能大于当前日期，请重新选择！");
                        return false;
                    }

                    if (beginTime.CompareTo(endTime) > 0)
                    {
                        EFWindow.Alert("开始日期不能大于结束日期，请重新选择！");
                        return false;
                    }
                }
                else if ((!startTime.Equals("")) && (stopTime.Equals("")))
                {
                    DateTime beginTime = Convert.ToDateTime(startTime);

                    if (beginTime.CompareTo(currentDate) > 0)
                    {
                        EFWindow.Alert("开始日期不能大于当前日期，请重新选择！");
                        return false;
                    }

                    fdEnd.Value = DateTime.Now.ToString(Common.DATETIME_FORMAT);
                    stopTime = DateTime.Now.ToString();
                }
                else if ((startTime.Equals("")) && (!stopTime.Equals("")))
                {
                    DateTime endTime = Convert.ToDateTime(stopTime);

                    if (endTime.CompareTo(currentDate) > 0)
                    {
                        EFWindow.Alert("结束日期不能大于当前日期，请重新选择！");
                        return false;
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// 查询设备效率信息
        /// </summary>
        /// <param name="block"></param>
        private void QueryOEEInfo(EIBlock block)
        {
            EIInfo inInfo = new EIInfo();

            inInfo.AddBlock(block);
            inInfo.Attributes[EIConstants.ServiceNameKey] = "ZMCEA0";
            inInfo.Attributes[EIConstants.MethodNameKey] = "queryOEEInfo";

            this.Submit(inInfo, QueryOEEInfoSubmitCompleted);
        }

        /// <summary>
        /// 返回设备OEE相关数据信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryOEEInfoSubmitCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                EFWindow.Alert("数据库查询错误，请检查服务器/数据库连接！");
                return;
            }
            else
            {
                EIInfo eiInfo = e.EIInfo;

                EIBlock equipmentBlock = eiInfo.GetBlock("equipment");
                EIBlock timeBlock = eiInfo.GetBlock("time");
                EIBlock loadBlock = eiInfo.GetBlock("load");

                if ((equipmentBlock != null) && (equipmentBlock.GetRowCount() > 0))
                {
                    IList<EIRow> equipmentList = equipmentBlock.GetRows();
                    IDictionary<string, EIRow> equipmentDic = new Dictionary<string, EIRow>();

                    for (int i = 0; i < equipmentList.Count; i++)
                    {
                        equipmentDic.Add(equipmentList[i]["fdKeyId"].ToString().Trim(), equipmentList[i]);
                    }

                    EIInfo outInfo = GenerateOEEInfo(equipmentDic, timeBlock, loadBlock);

                    this.equipmentOEEGrid.ItemsSource = null;
                    this.equipmentOEEGrid.UpdateData(outInfo);

                    Common.ClearChart(this.OEEChart);
                    Common.ClearChart(this.othersChart);
                }
                else
                {
                    this.equipmentOEEGrid.ItemsSource = null;

                    Common.ClearChart(this.OEEChart);
                    Common.ClearChart(this.othersChart);
                }
            }
        }

        /// <summary>
        /// 生成OEE分析数据EIInfo
        /// </summary>
        /// <param name="equipment"></param>
        /// <param name="operation"></param>
        /// <param name="fault"></param>
        private EIInfo GenerateOEEInfo(IDictionary<string, EIRow> equipmentDic, EIBlock time, EIBlock load)
        {
            EIInfo info = new EIInfo();
            EIBlock block = new EIBlock("OEEResult");
            Common.AddColumnToBlock(block, "fdNo");
            Common.AddColumnToBlock(block, "fdName");
            Common.AddColumnToBlock(block, "fdSystemName");
            Common.AddColumnToBlock(block, "fdMineName");
            Common.AddColumnToBlock(block, "fdAvailable");
            Common.AddColumnToBlock(block, "fdPerform");
            Common.AddColumnToBlock(block, "fdQuality");
            Common.AddColumnToBlock(block, "fdOEE");

            foreach (KeyValuePair<string, EIRow> item in equipmentDic)
            {
                string equipmentId = item.Key;
                EIRow row = item.Value;

                CalOEEData(row, equipmentId, time, load);

                block.AddRow(row);
            }

            block.Set(EIConstants.LimitKey, "10");      //设置EIblock的分页属性
            block.Set(EIConstants.OffsetKey, "0");
            block.Set(EIConstants.TotalRecordsKey, block.GetRowCount().ToString());
            block.Set(EIConstants.ShowCount, "true");

            info.AddBlock(block);

            return info;
        }

        /// <summary>
        /// 计算OEE各项数据
        /// </summary>
        /// <param name="row"></param>
        /// <param name="equipmentId"></param>
        /// <param name="time"></param>
        /// <param name="load"></param>
        private void CalOEEData(EIRow row, string equipmentId, EIBlock time, EIBlock load)
        {
            double sumRunTime = 0.0;

            IList<EIRow> timeList = time.GetRows();
            IList<EIRow> loadList = load.GetRows();

            if (timeList.Count > 0)
            {
                CalAvalibility(timeList, equipmentId, row, ref sumRunTime);   //计算可用度
            }
            else
            {
                row.Add("fdAvailable", Common.NO_RUN_RECORD);
            }

            if (loadList.Count > 0)
            {
                CalPerform(loadList, equipmentId, row, sumRunTime);   //计算性能比
            }
            else
            {
                row.Add("fdPerform", Common.NO_WORKLOAD_RECORD);
                row.Add("fdQuality", Common.NO_WORKLOAD_RECORD);
            }

            string _fdAvailable = row["fdAvailable"] == null ? "0" : row["fdAvailable"].ToString().Trim();
            string _fdPerform = row["fdPerform"] == null ? "0" : row["fdPerform"].ToString().Trim();
            string _fdQuality = row["fdQuality"] == null ? "0" : row["fdQuality"].ToString().Trim();

            if ((_fdAvailable.Equals(Common.NO_RUN_RECORD)) ||
                (_fdAvailable.Equals(Common.NO_WORKLOAD_RECORD)) ||
                (_fdPerform.Equals(Common.NO_RUN_RECORD)) ||
                (_fdPerform.Equals(Common.NO_WORKLOAD_RECORD)) ||
                (_fdQuality.Equals(Common.NO_RUN_RECORD)) ||
                (_fdQuality.Equals(Common.NO_WORKLOAD_RECORD)))
            {
                row.Add("fdOEE", Common.ZERO_RATIO);
            }
            else
            {
                _fdAvailable = "".Equals(_fdAvailable) ? "0" : _fdAvailable;
                _fdPerform = "".Equals(_fdPerform) ? "0" : _fdPerform;
                _fdQuality = "".Equals(_fdQuality) ? "0" : _fdQuality;

                double avail = Double.Parse(_fdAvailable.TrimEnd('%')) / 100;      //将百分数转换成小数
                double perform = Double.Parse(_fdPerform.TrimEnd('%')) / 100;
                double quality = Double.Parse(_fdQuality.TrimEnd('%')) / 100;

                string OEE = (avail * perform * quality * 100).ToString();      //计算OEE的百分比值

                row.Add("fdOEE", OEE);
                DecimalFilter(row, "fdOEE", 4);      //保存4位小数
            }
        }

        /// <summary>
        /// 计算可用度
        /// </summary>
        /// <param name="timeList"></param> 
        /// <param name="equipmentId"></param>
        /// <param name="row"></param>
        /// <param name="sumPlanTime"></param>
        /// <param name="sumDownTime"></param>
        private void CalAvalibility(IList<EIRow> timeList, string equipmentId, EIRow row,
            ref double sumRunTime)
        {
            double sumFaultDownTime = 0.0;

            var query = timeList.Where(p => p["fdKeyId"].ToString().Trim().Equals(equipmentId)).ToList();

            if (query.Count > 0)
            {
                foreach (var item in query)
                {
                    if ((item["fdSumRunTime"] != null) && (!item["fdSumRunTime"].ToString().Trim().Equals("")))
                    {
                        sumRunTime = Double.Parse(item["fdSumRunTime"].ToString().Trim());  //单位为分钟

                        if ((item["fdSumFaultDownTime"] == null) || (item["fdSumFaultDownTime"].ToString().Trim().Equals("")))
                        {
                            row.Add("fdAvailable", Common.HUNDRED_RATIO); //运行时时间不为null，故障停机时间为null
                        }
                        else          //故障停机时间不为空
                        {
                            sumFaultDownTime = Double.Parse(item["fdSumFaultDownTime"].ToString().Trim());
                            string avail = (sumRunTime * 100 / (sumRunTime + sumFaultDownTime)).ToString();

                            row.Add("fdAvailable", avail);
                            DecimalFilter(row, "fdAvailable", 4);
                        }
                    }
                    else
                    {
                        row.Add("fdAvailable", Common.NO_RUN_RECORD);
                        row.Add("fdPerform", Common.NO_RUN_RECORD);
                        row.Add("fdQuality", Common.NO_RUN_RECORD);
                        row.Add("fdOEE", Common.ZERO_RATIO);

                        return;
                    }
                }
            }
            else      //返回记录中无该设备ID/工作计划时间为空
            {
                row.Add("fdAvailable", Common.NO_RUN_RECORD);
                row.Add("fdPerform", Common.NO_RUN_RECORD);
                row.Add("fdQuality", Common.NO_RUN_RECORD);
                row.Add("fdOEE", Common.ZERO_RATIO);

                return;
            }
        }

        /// <summary>
        /// 计算性能比
        /// </summary>
        /// <param name="loadList"></param> 
        /// <param name="equipmentId"></param>
        /// <param name="row"></param>
        /// <param name="sumPlanTime"></param>
        /// <param name="sumDownTime"></param>
        private void CalPerform(IList<EIRow> loadList, string equipmentId, EIRow row,
            double sumRunTime)
        {
            var query = loadList.Where(p => p["fdKeyId"].ToString().Trim().Equals(equipmentId)).ToList();

            if(query.Count > 0)
            {
                foreach(var item in query)
                {
                    if ((item["fdSumWorkLoad"] != null) && (!item["fdSumWorkLoad"].ToString().Trim().Equals("")))
                    {
                        string _fdSumWorkLoad = "0";
                        string _fdTheoryPeriod = "0";
                        if (null != item["fdSumWorkLoad"] && !"".Equals(item["fdSumWorkLoad"]))
                        {
                            _fdSumWorkLoad = item["fdSumWorkLoad"].ToString().Trim();
                        }
                        if (null != item["_fdTheoryPeriod"] && !"".Equals(item["_fdTheoryPeriod"]))
                        {
                            _fdTheoryPeriod = item["_fdTheoryPeriod"].ToString().Trim();
                        }

                        double workLoad = Double.Parse(_fdSumWorkLoad);//工作量
                        double theoryPeriod = Double.Parse(_fdTheoryPeriod);//理论加工周期

                        if (sumRunTime > Common.EPSINON)//实际运行时长有效
                        {
                            string perform = (workLoad * theoryPeriod * 100 / sumRunTime).ToString();

                            row.Add("fdPerform", perform);
                            DecimalFilter(row, "fdPerform", 4);    //保存4位小数
                            row.Add("fdQuality", Common.HUNDRED_RATIO);   //性能比不为空，则优质率为1
                        }
                        else
                        {
                            row.Add("fdPerform", Common.NO_RUN_RECORD);
                            row.Add("fdQuality", Common.NO_RUN_RECORD);
                            row.Add("fdOEE", Common.ZERO_RATIO);
                            return;
                        }
                    }
                }
            }
            else      //返回记录中无该设备ID/工作量为空
            {
                row.Add("fdPerform", Common.NO_WORKLOAD_RECORD);
                row.Add("fdQuality", Common.NO_WORKLOAD_RECORD);
                row.Add("fdOEE", Common.ZERO_RATIO);

                return;
            }


        }

        #endregion

        #region 刷新RadChart统计图

        /// <summary>
        /// 勾选设备效率记录响应事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void equipmentOEEGrid_CheckChaged(object sender, CheckChangedEventArgs e)
        {
            timer.Interval = new TimeSpan(0, 0, 0, 0, 100);     //定时器时长：100ms
            timer.Tick += new EventHandler(GetCheckedRows);

            if (!timer.IsEnabled)
                timer.Start();
        }

        /// <summary>
        /// 获取勾选的设备效率记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetCheckedRows(object sender, EventArgs e)
        {
            if (timer != null)
            {
                timer.Stop();
            }

            IList<EIRow> checkedRows = this.equipmentOEEGrid.GetCheckedEIRows();

            if (checkedRows.Count > 0)
            {
                UpdateOEEChartData(this.OEEChart, checkedRows, chartType);
                UpdateOthersChartData(this.othersChart, checkedRows, chartType);
            }
            else
            {
                Common.ClearChart(this.OEEChart);
                Common.ClearChart(this.othersChart);

                return;
            }
        }

        /// <summary>
        /// 初始化RadChart图
        /// </summary>
        /// <param name="chartName"></param>
        /// <param name="title"></param>
        private void InitChart(RadChart chartName, string title)
        {
            chartName.DefaultView.ChartTitle.Content = title;
            chartName.DefaultView.ChartTitle.FontSize = 12;

            chartName.DefaultView.ChartLegend.Header = "";
            chartName.DefaultView.ChartLegend.FontSize = 8;
            chartName.DefaultView.ChartLegend.MaxWidth = 100;

            chartName.DefaultView.ChartArea.FontSize = 8;

            chartName.DefaultView.ChartArea.AxisX.LayoutMode = AxisLayoutMode.Inside;
            chartName.DefaultView.ChartArea.AxisX.AutoRange = true;
            chartName.DefaultView.ChartArea.AxisX.LabelRotationAngle = 45;
            chartName.DefaultView.ChartArea.AxisX.DefaultLabelFormat = "MMM-yy";

            chartName.DefaultView.ChartArea.AxisY.AutoRange = false;
            chartName.DefaultView.ChartArea.AxisY.MinValue = 0;
            chartName.DefaultView.ChartArea.AxisY.MaxValue = 1.1;
            chartName.DefaultView.ChartArea.AxisY.Step = 0.2;
            chartName.DefaultView.ChartArea.AxisY.DefaultLabelFormat = "#VAL{p0}";
            chartName.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            chartName.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Visible;
            chartName.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;

            chartName.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 刷新OEE统计分析图表
        /// </summary>
        /// <param name="chartName"></param>
        /// <param name="checkedRows"></param>
        private void UpdateOEEChartData(RadChart chartName, IList<EIRow> checkedRows, string chartType)
        {
            if (chartName.DefaultView.ChartArea.DataSeries != null)
            {
                chartName.DefaultView.ChartArea.AdditionalYAxes.Clear();
                chartName.DefaultView.ChartArea.DataSeries.Clear();
            }

            if (checkedRows.Count > 0)
            {
                chartName.DefaultView.ChartArea.DataSeries.Add(GenerateOEESeries(checkedRows, chartType));
            }
        }

        /// <summary>
        /// 刷新OEE各项指标的数据图表
        /// </summary>
        /// <param name="chartName"></param>
        /// <param name="checkedRows"></param>
        private void UpdateOthersChartData(RadChart chartName, IList<EIRow> checkedRows, string chartType)
        {
            if (chartName.DefaultView.ChartArea.DataSeries != null)
            {
                chartName.DefaultView.ChartArea.AdditionalYAxes.Clear();
                chartName.DefaultView.ChartArea.DataSeries.Clear();
            }

            if (checkedRows.Count > 0)
            {
                if (chartType.Equals(Common.CHART_PIE))
                {
                    EIRow row = this.equipmentOEEGrid.EIBlock.GetRow(this.equipmentOEEGrid.SelectedIndex);

                    if (row != null)
                    {
                        chartName.DefaultView.ChartArea.DataSeries.Add(GenerateOtherSeries(row, chartType));
                    }
                    else
                    {
                        chartName.DefaultView.ChartArea.DataSeries.Add(GenerateOtherSeries(checkedRows[0], chartType));
                    }
                }
                else
                {
                    for (int i = 0; i < checkedRows.Count; i++)
                    {
                        chartName.DefaultView.ChartArea.DataSeries.Add(GenerateOtherSeries(checkedRows[i], chartType));
                    }
                }
            }
        }

        /// <summary>
        /// 生成OEE统计分析图表的图
        /// </summary>
        /// <param name="data"></param>
        /// <param name="type"></param>
        private DataSeries GenerateOEESeries(IList<EIRow> data, string type)
        {
            DataSeries series = new DataSeries();

            switch (type)
            {
                case "Bar":
                    series.Definition = new BarSeriesDefinition();
                    AddDataToOEESeries(series, data);
                    break;
                case "Horizontal Bar":
                    series.Definition = new HorizontalBarSeriesDefinition();
                    AddDataToOEESeries(series, data);
                    break;
                case "Pie":
                    series.Definition = new PieSeriesDefinition();
                    series.Definition.AxisName = string.Empty;

                    series.Definition.ShowItemLabels = true;
                    series.Definition.ItemLabelFormat = "#VAL{p2} ";

                    for (int i = 0; i < data.Count; i++)
                    {
                        double value = Double.Parse(data[i]["fdOEE"].ToString().TrimEnd('%')) / 100;

                        series.Add(new DataPoint(value) { LegendLabel = data[i]["fdName"].ToString().Trim() });
                    }
                    break;
                default:
                    series.Definition = new BarSeriesDefinition();

                    AddDataToOEESeries(series, data);
                    break;
            }
            //series.Definition.AxisName = string.Empty;

            return series;
        }

        /// <summary>
        /// 添加OEE统计分析图表的数据
        /// </summary>
        /// <param name="series"></param>
        /// <param name="data"></param>
        private void AddDataToOEESeries(DataSeries series, IList<EIRow> data)
        {
            series.Definition.AxisName = string.Empty;
            series.Definition.ItemLabelFormat = "#VAL{p2}";
            series.Definition.LegendItemLabelFormat = "#XCAT";
            series.Definition.LegendDisplayMode = LegendDisplayMode.DataPointLabel;

            for (int i = 0; i < data.Count; i++)
            {
                EIRow row = data[i];

                string label = row["fdName"].ToString().Trim();
                double avgRecov = Double.Parse(row["fdOEE"].ToString().TrimEnd('%')) / 100;

                series.Add(new DataPoint(avgRecov) { LegendLabel = label, XCategory = label });
            }
        }

        /// <summary>
        /// 生成OEE各项指标图表的图
        /// </summary>
        /// <param name="chart"></param>
        /// <param name="title"></param>
        private DataSeries GenerateOtherSeries(EIRow row, string type)
        {
            DataSeries series = new DataSeries();

            switch (type)
            {
                case "Bar":
                    series.Definition = new BarSeriesDefinition();
                    AddDataToOtherSeries(series, row);
                    break;
                case "Horizontal Bar":
                    series.Definition = new HorizontalBarSeriesDefinition();
                    AddDataToOtherSeries(series, row);
                    break;
                case "Pie":
                    series.Definition = new PieSeriesDefinition();
                    series.Definition.AxisName = string.Empty;

                    series.Definition.ShowItemLabels = true;
                    series.Definition.ItemLabelFormat = "#VAL{p2}";

                    double avial = GetRowValue(row, "fdAvailable");
                    double perform = GetRowValue(row, "fdPerform");
                    double quality = GetRowValue(row, "fdQuality");

                    series.Add(new DataPoint(avial) { LegendLabel = "可用度" });
                    series.Add(new DataPoint(perform) { LegendLabel = "性能比" });
                    series.Add(new DataPoint(quality) { LegendLabel = "合格率" });
                    break;
                default:
                    series.Definition = new BarSeriesDefinition();
                    AddDataToOtherSeries(series, row);
                    break;
            }
            //series.Definition.AxisName = string.Empty;

            return series;
        }

        /// <summary>
        /// 添加OEE各项指标图表的数据
        /// </summary>
        /// <param name="chart"></param>
        /// <param name="title"></param>
        private void AddDataToOtherSeries(DataSeries series, EIRow row)
        {
            series.Definition.AxisName = string.Empty;
            series.Definition.ItemLabelFormat = "#VAL{p2}";

            series.LegendLabel = row["fdName"].ToString().Trim();

            double avial = GetRowValue(row, "fdAvailable");
            double perform = GetRowValue(row, "fdPerform");
            double quality = GetRowValue(row, "fdQuality");

            series.Add(new DataPoint(avial) { XCategory = "可用度" });
            series.Add(new DataPoint(perform) { XCategory = "性能比" });
            series.Add(new DataPoint(quality) { XCategory = "合格率" });
        }

        /// <summary>
        /// 点击图表类型按钮时的事件响应
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;

            if (btn != null)
            {
                btn.Focus();

                if (chartType.Equals(btn.Tag.ToString().Trim()))
                {
                    return;
                }
                else
                {
                    chartType = btn.Tag.ToString().Trim();
                }
            }
            else
            {
                return;
            }

            IList<EIRow> list = this.equipmentOEEGrid.GetCheckedEIRows();

            if (list.Count > 0)
            {
                switch (chartType)
                {
                    case "Bar":
                        UpdateOEEChartData(this.OEEChart, this.equipmentOEEGrid.GetCheckedEIRows(), Common.CHART_BAR);
                        UpdateOthersChartData(this.othersChart, this.equipmentOEEGrid.GetCheckedEIRows(), Common.CHART_BAR);
                        break;
                    case "Horizontal Bar":
                        UpdateOEEChartData(this.OEEChart, this.equipmentOEEGrid.GetCheckedEIRows(), Common.CHART_HORIZONTALBAR);
                        UpdateOthersChartData(this.othersChart, this.equipmentOEEGrid.GetCheckedEIRows(), Common.CHART_HORIZONTALBAR);
                        break;
                    case "Pie":
                        UpdateOEEChartData(this.OEEChart, this.equipmentOEEGrid.GetCheckedEIRows(), Common.CHART_PIE);
                        UpdateOthersChartData(this.othersChart, this.equipmentOEEGrid.GetCheckedEIRows(), Common.CHART_PIE);
                        break;
                    default:
                        UpdateOEEChartData(this.OEEChart, this.equipmentOEEGrid.GetCheckedEIRows(), Common.CHART_BAR);
                        UpdateOthersChartData(this.othersChart, this.equipmentOEEGrid.GetCheckedEIRows(), Common.CHART_BAR);
                        break;
                }
            }
        }

        /// <summary>
        /// 选择不同的OEE数据记录时，刷新饼状图事件响应
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void equipmentOEEGrid_SelectionChanged(object sender, SelectionChangeEventArgs e)
        {
            EIRow selectRow = this.equipmentOEEGrid.EIBlock.GetRow(this.equipmentOEEGrid.SelectedIndex);

            if ((selectRow != null) && (chartType.Equals(Common.CHART_PIE)))
            {
                UpdateOthersChartData(this.othersChart, this.equipmentOEEGrid.GetCheckedEIRows(), Common.CHART_PIE);
            }
        }

        #endregion

        #region 辅助函数

        /// <summary>
        /// 保留小数
        /// </summary>
        /// <param name="row"></param>
        /// <param name="index"></param>
        /// <param name="bits"></param>
        public void DecimalFilter(EIRow row, string index, int bits)
        {
            string tmp = row[index] == null ? "" : row[index].ToString().Trim();

            string[] split = tmp.Split('.');

            if (split.Length > 1)
            {
                if (split[1].Length > bits)
                {
                    tmp = tmp.Substring(0, tmp.IndexOf('.') + bits + 1);
                    row.Add(index, tmp + "%");
                }
                else
                {
                    row.Add(index, tmp + "%");
                }
            }
            else
            {
                row.Add(index, tmp + "%");
            }
        }

        /// <summary>
        /// 获取EIRow中的百分比值字段
        /// </summary>
        /// <param name="chartName"></param>
        private double GetRowValue(EIRow row, string index)
        {
            double result = 0.0;
            if (null == row[index])
            {
                return result;
            }

            string tmp = row[index].ToString().Trim();

            if (tmp.Equals(Common.NO_RUN_RECORD) || tmp.Equals(Common.NO_WORKLOAD_RECORD))
            {
                return result;
            }
            else
            {
                result = Double.Parse(tmp.TrimEnd('%')) / 100;
            }

            return result;
        }

        #endregion





    }
}
